package com.qianfeng.wuyang.himalaya.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;

import com.qianfeng.wuyang.himalaya.R;
import com.qianfeng.wuyang.himalaya.adapter.broadcastadapter.NationalRecyclerAdapter;
import com.qianfeng.wuyang.himalaya.bean.broadcastbean.NationEntity;
import com.qianfeng.wuyang.himalaya.bean.broadcastbean.ProvinceListEntity;
import com.qianfeng.wuyang.himalaya.bean.broadcastbean.ProvinceListResultEntity;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LocalActivity extends AppCompatActivity implements View.OnClickListener, LocationName, Callback<ProvinceListEntity> {
    private RecyclerView recycler_LocalActivity;
    private ImageView back;
    private String province;
    private int ProvinceCode;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    MyLocationListener mylocation= (MyLocationListener) myListener;
    private List<ProvinceListResultEntity> provinceList;
    private NationalRecyclerAdapter LocalRecyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_local);
        initView();
        //百度地图6.0以上权限申请
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE},0);

        }else{
            //有权限执行操作
            mylocation.setLocationName(this);
            mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
            mLocationClient.registerLocationListener( myListener );    //注册监听函数
            initLocation();
            mLocationClient.start();
        }


        //下载省市集合
        new Retrofit.Builder()
                .baseUrl("http://live.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(BCProvinceService.class)
                .getList().enqueue(this);

    }
    private void initView() {
        recycler_LocalActivity = ((RecyclerView) findViewById(R.id.recycler_LocalActivity));
        back = ((ImageView) findViewById(R.id.image_back));
        back.setOnClickListener(this);
        provinceList  = new ArrayList<>();
    }

    @Override
    public void onClick(View view) {
        finish();
    }
        //定位的设置
        private void initLocation() {
    LocationClientOption option = new LocationClientOption();
    option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
    );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
    option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系

    option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
    option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
    option.setOpenGps(true);//可选，默认false,设置是否使用gps
    option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
    option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
    option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
    option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
    option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
    option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
    mLocationClient.setLocOption(option);
    }

    @Override
    public void getCity(String city) {
        if (city != null) {
            province = city.substring(0,city.length()-1);
            Toast.makeText(this,"你当前所在的位置为："+province, Toast.LENGTH_SHORT).show();
            if (provinceList.size()!=0 && !province.equals("")) {
            for (int i = 0; i <provinceList.size(); i++) {
                if (province.equals(provinceList.get(i).getProvinceName())){
                    ProvinceCode = provinceList.get(i).getProvinceCode();
                }
            }
        }
            //数据下载到之后开启下载本地电台的异步
            MyApplication myApplication = (MyApplication)getApplication();
            LocalRecyclerAdapter = new NationalRecyclerAdapter(this);
            recycler_LocalActivity.setAdapter(LocalRecyclerAdapter);
            myApplication.getBcProvinceService().getData(1,20,ProvinceCode,2).enqueue(new Callback<NationEntity>() {
                @Override
                public void onResponse(Call<NationEntity> call, Response<NationEntity> response) {
//                    Toast.makeText(LocalActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                    if (response.body().getResult() != null) {
                        LocalRecyclerAdapter.addAll(response.body().getResult());
                    }

                }

                @Override
                public void onFailure(Call<NationEntity> call, Throwable t) {

                }
            });

        }
    }



    @Override
    public void onResponse(Call<ProvinceListEntity> call, Response<ProvinceListEntity> response) {
//        Toast.makeText(this, ""+response.body().getResult().size(), Toast.LENGTH_SHORT).show();
        provinceList.addAll(response.body().getResult());

    }

    @Override
    public void onFailure(Call<ProvinceListEntity> call, Throwable t) {

    }

    //权限申请结果的回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                && grantResults[1] == PackageManager.PERMISSION_GRANTED
                && grantResults[2] == PackageManager.PERMISSION_GRANTED
                && grantResults[3] == PackageManager.PERMISSION_GRANTED) {
            //权限申请成功执行相应操作
            mylocation.setLocationName(this);
            mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
            mLocationClient.registerLocationListener( myListener );    //注册监听函数
            initLocation();
            mLocationClient.start();

        }else{
            finish();
        }
    }
}
